// import fs from 'fs';
let dir = "token";
let json;

// fs.open(dir,"a+",function (err,fd) {
//
//     if(err){
//
//         fs.chmod(dir,0x777,(err)=>{
//             console.log(err)
//         })
//     }
// } );

let ConstJsonManager = {

  get(key){

    return  new Promise((resolve, reject) => {


      if(json){

        resolve(json[key]);
        return
      }

      let data = localStorage.getItem(dir);

      if(!data || data.length === 0){

        resolve();
        return
      }

      if(json){

        resolve(json[key]);
        return;
      }

      json = JSON.parse(data);
      resolve(json[key]);
      // fs.readFile(dir,(err,data) => {
      //
      //     if(!data || data.length === 0){
      //
      //         resolve();
      //         return
      //     }
      //
      //     if(json){
      //
      //         resolve(json[key]);
      //         return;
      //     }
      //
      //     json = JSON.parse( data.toString());
      //     resolve(json[key]);
      // })
    })
  },
  set(key ,val){

    return new Promise((resolve, reject) => {

      if(!json){
        json = {};
      }
      json[key] = val;
      updJson();
      resolve();

    })
  }
};



let updJson = (function () {


  let upd = false;
  let transferStr;

  return function(){

    if(upd){

      return;
    }
    upd = true;
    transferStr =  JSON.stringify(json);
    localStorage.setItem(dir, JSON.stringify(json));
    upd = false;
    if(transferStr !== JSON.stringify(json)){
      updJson()
    }

    // fs.writeFile(dir, JSON.stringify(json), 'utf8', (res) => {
    //
    //     upd = false;
    //     if(transferStr != JSON.stringify(json)){
    //         updJson()
    //     }
    //    });
  }
})();


export {ConstJsonManager};
